package control;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ContainerEvent;
import java.awt.event.ContainerListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.AbstractAction;
import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;

import view.AbstractContentJPanel;
import view.NotCloseableException;

@SuppressWarnings("serial")
public class CloseAllTabsAction extends AbstractAction {
	JTabbedPane pane;

	public CloseAllTabsAction(JTabbedPane tabbedPane) {
		super("Alle Tabs schliessen");
		pane = tabbedPane;
		putValue(
				ACCELERATOR_KEY,
				KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_MASK
						| InputEvent.SHIFT_MASK));
		pane.addContainerListener(new ContainerListener() {
			@Override
			public void componentRemoved(ContainerEvent e) {
				updateEnabled();
			}
			
			@Override
			public void componentAdded(ContainerEvent e) {
				updateEnabled();
			}
		});

		updateEnabled();
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		for (Component c : pane.getComponents()) {
			if (c instanceof AbstractContentJPanel) {
				AbstractContentJPanel panel = (AbstractContentJPanel) c;
				try {
					panel.tryToClose();
				} catch (NotCloseableException e1) {}
			}
		}
	}

	private void updateEnabled() {
		boolean hasCloseablePanels = false;

		for (Component c : pane.getComponents()) {
			if (c instanceof AbstractContentJPanel) {
				AbstractContentJPanel panel = (AbstractContentJPanel) c;
				if (panel.isCloseable()) {
					hasCloseablePanels = true;
					break;
				}
			}
		}

		setEnabled(hasCloseablePanels);
	}
}
